package org.example.shoppingsystem.config;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;

@WebFilter("/*")
public class CustomEncodingFilter implements Filter {

    private String encoding = "UTF-8";
    private boolean ignore = true;

    @Override



    public void init(FilterConfig config) {
        String encodingParam = config.getInitParameter("encoding");
        if (encodingParam != null) {
            this.encoding = encodingParam;
        }
        String ignoreParam = config.getInitParameter("ignore");
        this.ignore = (ignoreParam == null) || Boolean.parseBoolean(ignoreParam);
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {

        if (ignore || req.getCharacterEncoding() == null) {
            req.setCharacterEncoding(encoding);
        }
        resp.setCharacterEncoding(encoding);
        resp.setContentType("text/html;charset=" + encoding);

        chain.doFilter(req, resp);
    }

    @Override
    public void destroy() {}
}